package mroute

import (
	"github.com/gin-gonic/gin"
	"mygo/mymongo"
	"mygo/mystruct"
	"path/filepath"
	"os"
	"fmt"
	"encoding/json"
	"mygo/myws"
	"mygo/mylog"
	"mygo/mauth"
	"mygo/global"
	"strconv"
)

/* =================================================================================
   API操作接口
*/
// 添加
func MyApiAdd(cont *gin.Context) {
	var make_map mystruct.ModelItem
	if err := cont.ShouldBindJSON(&make_map); err != nil {
		cont.JSON(mystruct.StatusBadRequest, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
		return
	}
	chcae_str := ""
	for _, v := range make_map.Data {
		switch v.Value {
			case "code", "_id", "limit", "page", "apiid", "start_time", "stop_time", "value", "model", "field":
				chcae_str = v.Value
				break
			default:
				//
		}
	}
	if chcae_str != "" {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": fmt.Sprintf("[ %s ]保留字段禁止设置", chcae_str)})
		return
	}
		
	ret := mymongo.MyMonDB.ApiCur.Add(make_map)
	json_data, _ := json.Marshal(make_map)
	mesg := myws.Mesg{
		Type: "Addapi",
		Code: ret.Code,
		Api: "/api/addapi",
		Msg: ret.Mesg,
		Data: json_data,
	}
	go myws.SendWs(mesg)
	mylog.MyLog(mesg, cont.Request.RemoteAddr, global.Mtoken.Log_Path)
	cont.JSON(mystruct.StatusOK, gin.H{"code": ret.Code, "msg": ret.Mesg})
}
// 查询单条
func MyApiGet(cont *gin.Context) {
	apiid := cont.PostForm("apiid")
	res, ret := mymongo.MyMonDB.ApiCur.Get(apiid)
	if res.Code != 1 {
		cont.JSON(mystruct.StatusOK, gin.H{"code": res.Code, "msg": res.Mesg})
		return
	}
	cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": ret})
}
// 修改
func MyApiSet(cont *gin.Context) {
	apiid := cont.PostForm("apiid")
	field := cont.PostForm("field")
	value := cont.PostForm("value")
	var setvalue interface{}
	var val_join string
	switch field {
		case "authority":
			var json_data map[string]interface{}
			json.Unmarshal([]byte(value), &json_data)
			val_join = fmt.Sprintf("authority.%s.%s", json_data["select"], json_data["field"])
			setvalue = json_data["value"]
		case "sort":
			setvalue, _ = strconv.ParseInt(value, 10, 64)
			val_join = field
		case "data":
			var json_data map[string]string
			json.Unmarshal([]byte(value), &json_data)
			val_join = fmt.Sprintf("data.%s.%s", json_data["index"], json_data["field"])
			setvalue = json_data["value"]
		default:
			setvalue = value
			val_join = field
	}
	ret := mymongo.MyMonDB.ApiCur.Set(apiid, val_join, setvalue)
	json_data, _ := json.Marshal(map[string]string{
		"apiid": apiid,
		"field": val_join,
		"value": fmt.Sprintf("%s", setvalue)})
	mesg := myws.Mesg{
		Type: "Setapi",
		Code: ret.Code,
		Api: "/api/setapi",
		Msg: ret.Mesg,
		Data: json_data,
	}
	go myws.SendWs(mesg)
	mylog.MyLog(mesg, cont.Request.RemoteAddr, global.Mtoken.Log_Path)
	cont.JSON(mystruct.StatusOK, gin.H{"code": ret.Code, "msg": ret.Mesg})
}
// 查询
func MyApiSeeAll(cont *gin.Context) {
	code := cont.PostForm("code")
	var res *mystruct.Retdate
	var ret interface{}
	switch code {
		case "see":
			Muserboot := mauth.Get_token(cont)
			if Muserboot == nil {
				return
			}
			res_type, ret_data := mymongo.MyMonDB.ApiCur.See()
			var ret_list []mystruct.ModelItem
			for _, val := range ret_data {
				bot_type := mauth.Get_auth(Muserboot, &val)
				if bot_type.See {
					ret_list = append(ret_list, val)
				}
			}
			ret = ret_list
			res = res_type
		case "all":
			Muserboot := mauth.Get_token(cont)
			if Muserboot == nil {
				return
			}
			if Muserboot.Standing > mystruct.AUTH_Administrator {
				field := cont.PostForm("field")
				if field != "" {
					res, ret = mymongo.MyMonDB.ApiCur.All(field, cont.PostForm(field))
				}else{
					res, ret = mymongo.MyMonDB.ApiCur.See()
				}
			}else if Muserboot.Standing > mystruct.AUTH_Tourist {
				res, ret = mymongo.MyMonDB.ApiCur.All("account", Muserboot.Account)
			}
		case "check": 
			//检查设置字段值是否重复
			field := cont.PostForm("field")
			value := cont.PostForm("value")
			res, ret = mymongo.MyMonDB.ApiCur.Check(field, value)
	}
	if res.Code == 1 {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": ret})
	}else{
		cont.JSON(mystruct.StatusOK, gin.H{"code": res.Code, "msg": res.Mesg})
	}
}
// 删除
func MyApiDel(cont *gin.Context) {
	apiid := cont.PostForm("apiid")
	ret := mymongo.MyMonDB.ApiCur.Del(apiid)
	m_path := filepath.Join(global.Mtoken.Download_Path, apiid)
	if ret.Code == 1 || mystruct.Exists(m_path) {
		mfile_path := filepath.Join(global.Mtoken.File_Path, apiid)
		if mystruct.Exists(mfile_path) {
			os.RemoveAll(mfile_path)
		}
		os.RemoveAll(m_path)
	}
	json_data, _ := json.Marshal(map[string]string{"apiid": apiid})
	mesg := myws.Mesg{
		Type: "Delapi",
		Code: ret.Code,
		Api: "/api/delapi",
		Msg: ret.Mesg,
		Data: json_data,
	}
	go myws.SendWs(mesg)
	mylog.MyLog(mesg, cont.Request.RemoteAddr, global.Mtoken.Log_Path)
	cont.JSON(mystruct.StatusOK, gin.H{"code": ret.Code, "msg": ret.Mesg})
}